package webapp.frontOffice.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modele.utilisateur.Investisseur;
import webapp.tools.Auth;
import dao.utilisateur.InvestisseurDAO;


@WebServlet("/inscription")
public class Inscription extends HttpServlet
{
	private static final long serialVersionUID = 5508157763416502644L;
	
	public Inscription() {}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        if(Auth.isAuth(request.getSession()))
        {
            response.sendRedirect("index.jsp");
        }
        else    //Forward vers la vue
        {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/viewFrontoffice/inscription.jsp");
            dispatcher.forward(request, response);
        }
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		request.setCharacterEncoding("UTF-8");
		Investisseur user = new Investisseur();
		user.setAdresse(request.getParameter("adresse"));
		user.setCodePostal(request.getParameter("cp"));
		user.setDateNaissance(request.getParameter("dateNaissance"));
		user.setEmail(request.getParameter("email"));
		user.setEtatProfil(false);
		user.setLogin(request.getParameter("login"));
		user.setMdp(request.getParameter("mdp"));
		user.setNom(request.getParameter("nom"));
		user.setPrenom(request.getParameter("prenom"));
		user.setTelephone(request.getParameter("tel"));
		user.setVille(request.getParameter("ville"));
		
		try
		{
			new InvestisseurDAO().create(user);
			request.setAttribute("error", "Votre compte a été créé. Il doit être validé par un administrateur avant de pouvoir être utilisé.");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/viewFrontoffice/inscription.jsp");
            dispatcher.forward(request, response);
		}
		catch(Exception e)
		{
			request.setAttribute("error", "Nom d'utilisateur déjà existant");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/viewFrontoffice/inscription.jsp");
            dispatcher.forward(request, response);
		}
		
		
	}

}
